import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/lib/table/interface";

import UpdateModal from "./components/UpdateModal";
import {
  deleteRecordUsingPOST,
  listRecordByPageUsingPOST,
  updateRecordUsingPOST
} from "@/services/api/fileRecordController";


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.FileRecord>();
  const [selectedRowsState, setSelectedRows] = useState<API.FileRecord[]>([]);


  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.FileRecordUpdateRequest) => {
    const hide = message.loading('修改中');
    try {
      await updateRecordUsingPOST({
        ...fields
      });
      hide();
      message.success('修改成功');
      return true;
    } catch (error: any) {
      hide();
      message.error('修改失败. ' + error.message);
      return false;
    }
  };


  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.FileRecord) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteRecordUsingPOST({
        id: record.id,
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();  //自动刷新
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败. ' + error.message);
      return false;
    }
  };


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.FileRecord>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
    },
    {
      title: '用户编号',
      dataIndex: 'userId',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '输入文件路径',
      dataIndex: 'inputPath',
      valueType: 'textarea',
      ellipsis: true,
      copyable: true,
      hideInSearch: true,
    },
    {
      disable: true,
      title: '操作类型',
      dataIndex: 'doType',
      valueType: 'select',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueEnum: {
        json2csv: {text: 'json2csv', status: 'Success'},
        json2xml: {
          text: 'json2xml',
          status: 'Success',
        },
        json2yaml: {
          text: 'json2yaml',
          status: 'Success',
        },
        jsonFormat: {text: 'jsonFormat', status: 'Success'},
        jsonValid: {
          text: 'jsonValid',
          status: 'Success',
        },
        csv2json: {text: 'csv2json', status: 'Success'},
        csv2xml: {
          text: 'csv2xml',
          status: 'Default',
        },
        csv2yaml: {
          text: 'csv2yaml',
          status: 'Default',
        },
        csvFormat: {text: 'csvFormat', status: 'Default'},
        csvValid: {
          text: 'csvValid',
          status: 'Default',
        },
        xml2json: {text: 'xml2json', status: 'Processing'},
        xml2csv: {
          text: 'xml2csv',
          status: 'Processing',
        },
        xml2yaml: {
          text: 'xml2yaml',
          status: 'Processing',
        },
        xmlFormat: {text: 'xmlFormat', status: 'Processing'},
        xmlValid: {
          text: 'xmlValid',
          status: 'Processing',
        },
        yaml2json: {text: 'yaml2json', status: 'Error'},
        yaml2csv: {
          text: 'yaml2csv',
          status: 'Error',
        },
        yaml2xml: {
          text: 'yaml2xml',
          status: 'Error',
        },
        yamlFormat: {text: 'yamlFormat', status: 'Error'},
        yamlValid: {
          text: 'yamlValid',
          status: 'Error',
        },
      },
    },
    {
      title: '输出文件路径',
      dataIndex: 'outputPath',
      valueType: 'textarea',
      ellipsis: true,
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'date',
      hideInSearch: true,
      hideInForm: true,
      sorter: true,
    },

    {
      disable: true,
      title: '状态',
      dataIndex: 'recordStatus',
      filters: true,
      onFilter: true,
      ellipsis: true,
      hideInForm: true,
      valueType: 'select',
      valueEnum: {
        0: {text: '成功', status: 'Success'},
        1: {
          text: '失败',
          status: 'Error',
        },
        2: {
          text: '异常',
          status: 'Processing',
        },
      },
    },
    {
      title: '修改',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: API.FileRecordQueryRequest) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <Button
          type='text'
          danger
          key="remove"
          onClick={() => {
            handleRemove(record);
          }}>
          删除
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <div style={{maxHeight: 'calc(100vh - 220px)', minHeight: 'calc(100vh - 220px)', overflow: 'auto'}}>
        <ProTable<API.FileRecord, API.BaseResponsePageFileRecord_>
          headerTitle={'记录表格'}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}

          request={async (
            params,
            sort: Record<string, SortOrder>,
            filter: Record<string, React.ReactText[] | null>,
          ) => {
            const res: any = await listRecordByPageUsingPOST({
              ...params,
            });
            if (res?.data) {
              return {
                data: res?.data.records || [],
                success: true,
                total: res?.data.total || 0,
              };
            } else {
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          columns={columns}
          pagination={{
            pageSize: 8,
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.doType && (
          <ProDescriptions<API.FileRecord>
            column={2}
            title={currentRow?.doType}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.doType,
            }}
            columns={columns as ProDescriptionsItemProps<API.FileRecord>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default TableList;
